<template>
  <div class="login">
    <h1>登录</h1>
    <el-form @submit.prevent="handleLogin" :rules="rules" ref="form">
      <el-form-item label="用户名" :error="usernameError">
        <el-input
          v-model="username"
          placeholder="输入用户名"
          required
        ></el-input>
        <div v-if="usernameError" class="error-message">{{ usernameError }}</div>
      </el-form-item>
      
      <el-form-item label="密码" :error="passwordError">
        <el-input
          type="password"
          v-model="password"
          placeholder="输入密码"
          required
        ></el-input>
        <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" native-type="submit">登录</el-button>
        <div v-if="loginError" class="error-message">{{ loginError }}</div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      usernameError: '',
      passwordError: '',
      loginError: '',
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    handleLogin() {
      this.usernameError = '';
      this.passwordError = '';
      this.loginError = '';

      // 简单的表单验证
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        
        if (this.username === 'rice' && this.password === 'rice') {
          alert('登录成功');
          this.$router.push('/');
        } else {
          this.loginError = '用户名或密码错误';
        }
      });
    }
  }
};
</script>

<style scoped>
.login {
  max-width: 400px;
  margin: auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}
</style>